from requests.models import codes
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import wait
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import random
import time
import pymysql
import os
import sqlite3
import pathlib
import urllib3
import uuid 
from chaojiying import *
import ddddocr

root=pathlib.Path(__file__).parent
sqlType="mysql" #sqlite
CorrectRate=0.85
userinfo=None
ocr = ddddocr.DdddOcr()
# sqlType="sqlite" 
tm=[0.3, 0.3, 0.3, 0.5, 0.5, 0.5, 0.5, 0.3, 0.8, 0.3, 0.3, 0.3, 0.3, 0.5, 0.5, 0.2, 0.4, 0.3, 0.6, 0.5, 0.5, 0.4, 0.5, 0.6, 0.6, 0.6, 0.4, 0.3, 0.3, 0.4, 0.3, 0.5, 0.4, 0.3, 0.3, 0.4, 0.3, 0.6, 0.6, 0.5, 0.6, 0.5, 0.6, 0.6, 0.5, 0.7, 0.3, 0.6, 0.5, 0.3, 0.2, 0.2, 0.4, 0.5, 0.6, 0.5, 0.5, 0.2, 0.5, 0.3, 0.2, 0.4, 0.2, 0.2, 0.2, 0.2, 0.3, 0.2, 0.2, 0.2, 0.6, 0.4, 0.3, 0.5, 0.3, 0.5, 0.2, 0.6, 0.4, 0.2, 0.3, 0.2, 0.2, 0.7, 0, 0.3, 0.5, 0.6, 0.5, 0.5, 0.2, 0.7, 0.5, 0.5, 0.5, 0.7, 0.1, 0.6, 0.2, 0.4,0.4]

if (sqlType=="mysql"):
    hostnamelist = ['192.168.2.247',"172.16.2.174","192.168.8.247"] #example
    for i in hostnamelist:
        response = os.system(f"ping -n 1 -w 500 {i}" )
        if response == 0:
            print(f"connect {i}")
            try:
                db = pymysql.connect(
                    host=i
                    ,user='xjzx'
                    ,password='Af1121113'
                    ,db='2class'
                    ,charset='utf8')
            except:
                print(f"mysql {i} connect error!")
                exit()
            break
        else:
            print (i, 'is down!')
elif(sqlType=="sqlite"):
    db=sqlite3.connect(str(root/"zhidi.db"))
cur = db.cursor()
chaojiying = Chaojiying_Client('zthubo', 'Af1121113', '924076')
def init():
    global driver
    driver = webdriver.Chrome()
    driver.set_window_size(1200, 1000)
    # driver.maximize_window()
    return driver

def getShortId():
    array = ["a", "b", "c", "d", "e", "f",
         "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
         "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
         "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
         "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
         "W", "X", "Y", "Z"]
    id = str(uuid.uuid4()).replace("-", '')
    buffer = []
    for i in range(8):
        start = i * 4
        end = i * 4 + 4
        val = int(id[start:end], 16)
        buffer.append(array[val % 62])
    return "".join(buffer)
def waitElement(xpath,waittime=10):
    try:
        WebDriverWait(driver,waittime).until(EC.visibility_of_element_located((By.XPATH,xpath)))
    except:
        return False
    else:
        return True

def getcodes():
    codes=None
    id=getShortId()
    time.sleep(1)
    if(not waitElement('//*[@id="captchaImg"]')):
        return False
    try:
        img1=driver.find_element(By.XPATH,'//*[@id="popLogin"]/div/form/div[5]/div[2]')
        img1.screenshot(id+'.jpg')
    except:
        print("error")
    else:
        im = open(id+'.jpg', 'rb').read()

        driver.find_element(By.XPATH,'//*[@id="popLogin"]/div/form/div[5]/div[1]/input').clear()
        # codes = chaojiying.PostPic(im, 1004) 
        # codes = chaojiying.PostPic(im, 8001)  #体验包（1元/24小时 500次）
        # print(codes)
        # codes=codes['pic_str']
        codes = ocr.classification(im)
        print(codes)
        driver.find_element(By.XPATH,'//*[@id="popLogin"]/div/form/div[5]/div[1]/input').send_keys(codes)
        # driver.find_element(By.XPATH,'//*[@id="popLogin"]/div/form/div[4]/div[1]/input').send_keys('pic_str')
        os.remove(id+'.jpg')
        return codes

def login(username='JZF530621200501132031'):
    
    driver.get("https://www.zhidiedu.com")
    if(not waitElement("/html/body/div[3]/div/div/div/a")):
        return False
    bntlogin=driver.find_element(By.XPATH,"/html/body/div[3]/div/div/div/a")
    bntlogin.click()
    p=driver.find_element(By.XPATH,"//*[@id=\"popLogin\"]/div/form/div[2]/ul/li[2]")
    p.click()
    driver.find_element(By.XPATH,'//*[@id="popLogin"]/div/form/div[3]/input').send_keys(username)
    pw=driver.find_element(By.XPATH,'//*[@id="popLogin"]/div/form/div[4]/input').send_keys("123456")
    ActionChains(driver).send_keys(Keys.PAGE_DOWN).perform()
    logb=driver.find_element(By.XPATH,'//*[@id="popLogin"]/div/form/div[6]/button')
    
    # WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH,'//*[@id="popLogin"]/div/form/div[5]/button')))
    #//*[@id="layui-layer15"]/div  验证码错误
    # actions = ActionChains(driver)
    # actions.move_to_element(logb)
    # actions.click(logb)
    # actions.perform()
    
    for i in range(5):
        codes=getcodes()
        logb.click()
        if(waitElement('/html/body/div[10]/div',2)):
            print("验证码错误！")
            time.sleep(1)
            # chaojiying.ReportError(codes['pic_id'])
        else:
            break
    return waitElement('//*[@id="layui-layer1"]/div[3]/a')
    
def begintest():
    
    if(not waitElement('//*[@id="LAY_bloglist"]/section/div[3]/a')):#开始测试
        return False
    driver.find_element(By.XPATH,'//*[@id="LAY_bloglist"]/section/div[3]/a').click()

    if(not waitElement('//*[@id="layui-layer1"]/div[3]/a')):
        return False
    
    ele=driver.find_element(By.XPATH,'//*[@id="testNeedKnow"]/p')
    ele.click()
    ActionChains(driver).send_keys(Keys.PAGE_DOWN).perform()
    time.sleep(1)

    driver.find_element(By.XPATH,'//*[@id="testNeedKnow"]/p/div').click()
    driver.find_element(By.XPATH,'//*[@id="layui-layer1"]/div[3]/a').click()
    time.sleep(0.5)
    # PHQ_9()
    MHT()

    return True
def MHT():
    n=1
    f=True
    while(f):
        ra=random.random()
        if(n>len(tm)):
            p=0.5
        else:
            p=tm[n-1]
        if(ra<=p):
            f=selects(1,n)
        else:
            f=selects(2,n)
        n=n+1

def PHQ_9():
    n=1
    f=None
    
    while(n<11):
        ra=random.random()
        if(n==8):
            f=selects(1,n)
        elif(n==9):
            f=selects(2,n)
        elif(n==10):
            f=selects(1,n)
        else:
            if(ra<0.80):
                f=selects(1,n)
            elif(ra<0.95):
                f=selects(2,n)
            elif(ra<1):
                f=selects(3,n)
            else:
                f=selects(4,n)
        if(not f):
            return False
        print(n)
        n=n+1

def selects(index,q):#/html/body/div[3]/div/div/div/article/section/form/div[1]/div[2]/div[2]/div/label[1]
    global driver
    if (not waitElement('//*[@id="ques_'+str(q)+'"]/label['+str(index)+']')):
        print("s error")
        print('//*[@id="ques_'+str(q)+'"]/label['+str(index)+']')
        return False
        
    driver.find_element(By.XPATH,'//*[@id="ques_'+str(q)+'"]/label['+str(index)+']').click()
    time.sleep(0.2)
    if(waitElement('//*[@id="nextTi"]',1)):
        driver.find_element(By.XPATH,'//*[@id="nextTi"]').click()
    else:
        driver.find_element(By.XPATH,'//*[@id="tj"]').click()
        time.sleep(1)
        driver.close
        driver=None
        return False       

    return True

def auto():
    cur.execute("select username from zhidi where c is null limit 1")
    d=cur.fetchone()
    while(not d == None):
        try:
            cur.execute("select username from zhidi where c is null limit 1")
            d=cur.fetchone()
            if( d == None):
                os._exit(0)
            else:
                username=str(d[0])
                sql="UPDATE zhidi SET c = '1' WHERE username = '{0}'".format(username)
                print(sql)
                cur.execute(sql)
                db.commit()
                driver=init()
                if(login(username)):
                    print("login successful!")

                    driver.find_element(By.XPATH,'//*[@id="layui-layer1"]/div[3]/a').click()

                else:
                    print('error')
                    driver.close()
                    driver=None
                    continue

                if(not begintest()):
                    driver.close()
                    driver=None
                    continue
        except:
            driver=None


if __name__ == "__main__" :
    auto()
    # driver=init()
    # if(login()):
    #     print("login successful!")
    #     driver.find_element(By.XPATH,'//*[@id="layui-layer1"]/div[3]/a').click()

    # else:
    #     print('error')
    # print(begintest())

    



    a=input()
    # //*[@id="ques_1"]/label[1]
    # //*[@id="ques_1"]/label[2]
    # //*[@id="nextTi"]
    # //*[@id="tj"]